<template>
    <div class="adressdetails">
      <van-nav-bar  
      @click-left="$router.back()"
      left-text="返回" 
      title="地址编辑"></van-nav-bar>
    
    <van-address-edit
      :area-list="areaList"
      :address-info="address"
      show-delete
      show-set-default
      show-search-result
      :search-result="searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
      @change-detail="onChangeDetail"
    />
</div>
</template>
<script>
import {ref,onMounted,computed} from 'vue'
import { areaList } from '@vant/area-data';
import {useStore} from 'vuex'
import {useRouter,useRoute} from 'vue-router'
import {get, post} from '../../../utils/request'
export default {
  setup(){
    const searchResult = ref([]);
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const address = ref({})
    
    let user_info = computed(()=> store.state.user.user_info)

    const onSave = async (content) => {
      let data = {
        id:content.id,
        realname:content.name,
        telephone:content.tel,
        province:content.province,
        city:content.city,
        area:content.county,
        address:content.addressDetail,
        isDefault:Number(content.isDefault),
        areaCode:content.areaCode,
        userId:user_info.value.id
      }
      let allAddress = [];
      let resp = await get('/app/address/queryByUserId',{userId:user_info.value.id});
      allAddress = resp.data;
      // 如果把当前地址设为默认，则取消其他默认地址
      // 如果当前本就是默认，设为非默认，则把第一个地址设为默认
      if(data.isDefault){
        allAddress.forEach((item)=>{
          if(item.isDefault && item.id != data.id){
            item.isDefault = 0;
            post("/app/address/saveOrUpdate",item);
          }
        })
      }else{
          allAddress[0].isDefault = 1;
          post("/app/address/saveOrUpdate",allAddress[0]);
      }
      let url = "/app/address/saveOrUpdate"
      await post(url,data);
      await router.push('/address');
    };
    // 删除地址操作
    const onDelete = async (content) => {
      // 判断如果删除的地址是默认地址，则把地址列表的第一个设为默认地址
      if(content.isDefault){
        let allAddress = [];
        let resp = await get('/app/address/queryByUserId',{userId:user_info.value.id});
        allAddress = resp.data;
        allAddress[0].isDefault = 1;
        post("/app/address/saveOrUpdate",allAddress[0]);
      }

      let url ="/app/address/deleteById";
      await get(url,{id:content.id});
      router.push('/address');
    };

    onMounted(()=>{
      let params = route.params;
      if(params && params.address){
        let pca = params.address.split(' ');
        address.value = {
          ...params,
          province:pca[0],
          city:pca[1],
          county:pca[2],
          addressDetail:pca[3]
        };
      }

     
    })

    return {
      onSave,
      onDelete,
      areaList,
      searchResult,
      address
    };
  }
}
</script>
